import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppConsts } from '@shared/AppConsts';
import { ModuleDefinition, ModuleDto, ModuleServiceProxy, NameValue } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { finalize } from 'rxjs/operators';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { FeatureTreeComponent } from '../shared/feature-tree.component';
import { find as _find, forEach as _forEach, filter as _filter, remove as _remove } from 'lodash-es';
import { FeatureTreeEditModel } from '../shared/feature-tree-edit.model';
import { LookupContentConfigModalComponent } from './lookup-content-config-modal.component';

@Component({
    selector: 'create-or-edit-module-modal',
    templateUrl: './create-or-edit-module-modal.component.html'
})
export class CreateOrEditModuleModalComponent extends AppModalComponentBase {

    @ViewChild('modal', { static: true }) modal: ModalDirective;
    @ViewChild('featureTree') featureTree: FeatureTreeComponent;
    
    @ViewChild('LookupContentConfigModal', { static: true }) LookupContentConfigModal: LookupContentConfigModalComponent;

    @Output() callback: EventEmitter<any> = new EventEmitter<any>();

    saving = false;
    loading = false;
    title: string;

    data: ModuleDto;
    moduleDefinitions: ModuleDefinition[]
    featureTreeData:FeatureTreeEditModel;

    constructor(
        injector: Injector,
        private http: HttpClient,
        private _moduleService: ModuleServiceProxy
    ) {
        super(injector);
        this.data = new ModuleDto();

    }


    show(id: string, title: string) {

        this.title = title;
        this.data = new ModuleDto();
        this.modal.show();
        this.moduleDefinitions = [];
        this.loading = true;
        this._moduleService.get(id)
            .pipe(finalize(() => this.loading = false))
            .subscribe(result => {
                if (result.module) {
                    this.data = result.module;
                    this.title += '(' + this.data.id + ')';
                }
                
                if (!this.data.target) {
                    this.data.target = '';
                }

                this.featureTreeData = {
                    features: result.features,
                    featureValues: this.data.requiredFeatures? this.data.requiredFeatures.map(
                        t => new NameValue({ name: t, value: 'ture' })
                    ): []
                };
                this.featureTree.editData = this.featureTreeData;

                if (!this.data.name) {
                    this.data.name = "";
                }
                result.moduleDefinitions.unshift(
                    new ModuleDefinition({ name: "", displayName: this.l('UnSelect'), features: null })
                );
                this.moduleDefinitions = result.moduleDefinitions;
            });

    }

    close(): void {
        this.modal.hide();
    }



    save() {
        if (this.data.id) {
            this.saving = true;
            this._moduleService.update(this.data)
            .pipe(finalize(() => this.saving = false))
            .subscribe(result=> {
                this.notify.success(this.l('SavedSuccessfully'));
                this.callback.emit();
                this.close();
            });
        } else {
            this.saving = true;
            this._moduleService.create(this.data)
            .pipe(finalize(() => this.saving = false))
            .subscribe(result=>  {
                this.notify.success(this.l('SavedSuccessfully'));
                this.callback.emit();
                this.close();
            });
        }
    }

    moduleChanged() {
        let val = [];
        for (let i = 0; i < this.moduleDefinitions.length; i++) {
            let item = this.moduleDefinitions[i];
            if (item.name === this.data.name) {
                if (item.name) {
                    val = item.features.requiredFeatures;
                    this.data.requiresAll = item.features.requiresAll;
                } else {
                    this.data.requiresAll = true;
                }
                break;
            }
        }
        this.data.requiredFeatures = val;
        this.featureTreeData.featureValues = val? val.map(
            t => new NameValue({ name: t, value: 'ture' })
        ): [];
        this.featureTree.setSelectedNodes(this.featureTreeData);
    }

    lookupConfig() {
        this.LookupContentConfigModal.show('ContentDefinition','选择内容模块配置');
    }
    lookupCallback(result: string){
        this.data.customData = result;
    }
}
